import { BrowserRouter as Router, Routes, Route, Navigate, useLocation } from 'react-router-dom';
import { Sidebar } from '@/components/layout/sidebar';
import { AnalysisPage } from '@/components/pages/analysis-page';
import { ChartsPage } from '@/components/pages/charts-page';
import { ChartDetailPage } from '@/components/pages/chart-detail-page';
import { ProfilePage } from '@/components/pages/profile-page';
import { LoginForm } from '@/components/auth/login-form';
import { ThemeProvider } from '@/components/theme-provider';
import { AuthProvider, useAuth } from '@/contexts/auth-context';
import { Toaster } from '@/components/ui/toaster';
import { Button } from '@/components/ui/button';
import { LogOut, Loader2 } from 'lucide-react';

function MainLayout() {
  const location = useLocation();
  const { user, logout } = useAuth();

  const getPageTitle = () => {
    const path = location.pathname;
    if (path === '/analysis') return '智能分析';
    if (path === '/charts') return '我的图表';
    if (path.startsWith('/chart/')) return '图表详情';
    if (path === '/profile') return '个人中心';
    return '智能BI平台';
  };

  const getActiveTab = () => {
    const path = location.pathname;
    if (path === '/analysis') return 'analysis';
    if (path === '/charts' || path.startsWith('/chart/')) return 'charts';
    if (path === '/profile') return 'profile';
    return 'analysis';
  };

  return (
    <div className="flex h-screen bg-gray-50">
      <Sidebar activeTab={getActiveTab()} />
      <div className="flex-1 flex flex-col">
        {/* 顶部导航栏 */}
        <header className="bg-white border-b border-gray-200 px-6 py-4">
          <div className="flex items-center justify-between">
            <div>
              <h2 className="text-xl font-semibold text-gray-800">
                {getPageTitle()}
              </h2>
            </div>
            <div className="flex items-center space-x-4">
              <div className="flex items-center space-x-2">
                <div className="w-8 h-8 bg-blue-600 rounded-full flex items-center justify-center">
                  <span className="text-white text-sm font-medium">
                    {user?.userName?.charAt(0) || user?.userAccount?.charAt(0) || 'U'}
                  </span>
                </div>
                <div className="hidden md:block">
                  <p className="text-sm font-medium text-gray-700">
                    {user?.userName || user?.userAccount}
                  </p>
                  <p className="text-xs text-gray-500">
                    {user?.userRole === 'admin' ? '管理员' : '普通用户'}
                  </p>
                </div>
              </div>
              <Button
                variant="outline"
                size="sm"
                onClick={logout}
                className="text-red-600 hover:text-red-700 hover:bg-red-50"
              >
                <LogOut className="h-4 w-4 mr-2" />
                退出
              </Button>
            </div>
          </div>
        </header>

        {/* 主内容区域 */}
        <main className="flex-1 overflow-auto">
          <Routes>
            <Route path="/" element={<Navigate to="/analysis" replace />} />
            <Route path="/analysis" element={<AnalysisPage />} />
            <Route path="/charts" element={<ChartsPage />} />
            <Route path="/chart/:id" element={<ChartDetailPage />} />
            <Route path="/profile" element={<ProfilePage />} />
          </Routes>
        </main>
      </div>
    </div>
  );
}

function AppContent() {
  const { user, loading, login, logout, isAuthenticated } = useAuth();

  // 显示加载状态
  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-50">
        <div className="text-center">
          <Loader2 className="h-8 w-8 animate-spin text-blue-600 mx-auto mb-4" />
          <p className="text-gray-600">正在加载...</p>
        </div>
      </div>
    );
  }

  // 未登录时显示登录页面
  if (!isAuthenticated) {
    return <LoginForm onLoginSuccess={login} />;
  }

  return <MainLayout />;
}

function App() {
  return (
    <ThemeProvider defaultTheme="light" storageKey="vite-ui-theme">
      <AuthProvider>
        <Router>
          <AppContent />
          <Toaster />
        </Router>
      </AuthProvider>
    </ThemeProvider>
  );
}

export default App;